#include "eeprom.h"
#include "gpio_iic.h"

void eeprom_init(void)
{
	IIC_Init();
}

void eeprom_write_byte(u8 word_address, u8 data)
{
	IIC_Start();
	IIC_Send_Byte(EEPROM_ADDR | 0x0);
	IIC_Wait_Ack();
	IIC_Send_Byte(word_address);
	IIC_Wait_Ack();
	IIC_Send_Byte(data);
	IIC_Wait_Ack();
	IIC_Stop();
}

void eeprom_write_page(u8 word_address, u8 data[8])
{
	u8 i;
	
	IIC_Start();
	IIC_Send_Byte(EEPROM_ADDR | 0x0);
	IIC_Wait_Ack();
	IIC_Send_Byte(word_address);
	IIC_Wait_Ack();
	
	for (i = 0; i < 8; i++) {
		IIC_Send_Byte(data[i]);
		IIC_Wait_Ack();
	}
	IIC_Stop();
}

u8 eeprom_read_current(void)
{
	u8 data;
	
	IIC_Start();
	IIC_Send_Byte(EEPROM_ADDR | 0x1);
	IIC_Wait_Ack();
	data = IIC_Recv_Byte(0);
	IIC_Stop();
	
	return data;
}

u8 eeprom_read_random(u8 word_address)
{
	u8 data;
	
	IIC_Start();
	IIC_Send_Byte(EEPROM_ADDR | 0x0);
	IIC_Wait_Ack();
	IIC_Send_Byte(word_address);
	IIC_Wait_Ack();
	IIC_Start();
	IIC_Send_Byte(EEPROM_ADDR | 0x1);
	IIC_Wait_Ack();
	data = IIC_Recv_Byte(0);
	IIC_Stop();
	
	return data;
}

void eeprom_read_sequence(u8 *data, u8 n)
{
	u8 i;
	
	IIC_Start();
	IIC_Send_Byte(EEPROM_ADDR | 0x1);
	IIC_Wait_Ack();
	
	for (i = 0; i < n; i++) {
		if (i == n - 1) {
			data[i] = IIC_Recv_Byte(0);
		} else 
			data[i] = IIC_Recv_Byte(1);
	}
	IIC_Stop();
}



